import Mn from 'backbone.marionette';
import Bb from 'backbone';
import Radio from 'backbone.radio';

import StatusFormPopupView from 'common/views/StatusFormPopupView.js';
import SupplierOrderLineModel from '../models/SupplierOrderLineModel.js';
import SupplierOrderLineTableView from './SupplierOrderLineTableView.js';
import SupplierOrderLineFormPopupView from './SupplierOrderLineFormPopupView.js';
import SupplierOrderFormView from './SupplierOrderFormView.js';
import SupplierOrderLineDuplicateFormView from './SupplierOrderLineDuplicateFormView.js';
import TotalView from './TotalView.js';
import MessageView from 'base/views/MessageView.js';
import LoginView from 'base/views/LoginView.js';
import NodeFileCollectionView from 'common/views/NodeFileCollectionView.js';
import {displayServerSuccess, displayServerError} from 'backbone-tools.js';
import { getPercent } from 'math.js';
import { hideLoader, showLoader } from 'tools.js';
import ErrorView from 'base/views/ErrorView.js';

const MainView = Mn.View.extend({
    className: 'container-fluid page-content',
    template: require('./templates/MainView.mustache'),
    regions: {
        modalRegion: '.modalRegion',
        files: '.files',
        supplierOrderForm: '.supplier-order',
        linesRegion: '.lines-region',
        totals: '.totals',
        messages: {
            el: '.messages-container',
            replaceElement: true,
        },
        errors: '.group-errors',
    },
    childViewEvents: {
        'line:add': 'onLineAdd',
        'line:edit': 'onLineEdit',
        'line:delete': 'onLineDelete',
        'order:modified': 'onDataModified',
        'line:duplicate': 'onLineDuplicate',
        'status:change': 'onStatusChange',
    },
    onDataModified(name, value) {
        if (name == 'supplier_id') {
            this.onSupplierModified(value);
        }
        let totals = this.facade.request('get:model', 'total');
        let order = this.facade.request('get:model', 'supplierOrder');

        let ttc = totals.get('ttc');
        let ttc_cae = getPercent(ttc, order.get('cae_percentage'));
        let ttc_worker = ttc - ttc_cae;
        totals.set('ttc_cae', ttc_cae);
        totals.set('ttc_worker', ttc_worker);
    },
    onSupplierModified(supplier_id) {
        /* jQuery hack to update supplier static part
         * defined in supplier_order.mako
         */
        let suppliers = this.config.request('get:options', 'suppliers');
        let supplier = _.find(suppliers, x => x.value == supplier_id);

        let elA = $("[data-backbone-var=supplier_id]");
        elA.text(supplier.label);
        elA.attr('href', `/suppliers/${supplier_id}`);
    },
    initialize(){
        this.facade = Radio.channel('facade');
        this.config = Radio.channel('config');
        this.listenTo(this.facade, 'status:change', this.onStatusChange);
    },
    showSupplierOrderForm(){
        let edit = this.config.request('get:form_section', 'general')['edit'];

        var model = this.facade.request('get:model', 'supplierOrder');
        var view = new SupplierOrderFormView({
            model:model,
            edit: edit,
        });

        this.showChildView('supplierOrderForm', view);
    },
    onLineAdd(childView){
        var model = new SupplierOrderLineModel({});
        this.showLineForm(model, true, "Ajouter un achat");
    },
    onLineEdit(childView){
        this.showLineForm(childView.model, false, "Modifier un achat");
    },
    showLineForm(model, add, title){
        var view = new SupplierOrderLineFormPopupView({
            title: title,
            add:add,
            model:model,
            destCollection: this.facade.request('get:collection', 'lines'),
        });
        this.showChildView('modalRegion', view);
    },
    showDuplicateForm(model){
        var view = new SupplierOrderLineDuplicateFormView({model: model});
        this.showChildView('modalRegion', view);
    },
    onLineDuplicate(childView){
        this.showDuplicateForm(childView.model);
    },
    onDeleteSuccess: function(){
        displayServerSuccess("Vos données ont bien été supprimées");
    },
    onDeleteError: function(){
        displayServerError("Une erreur a été rencontrée lors de la " +
                            "suppression de cet élément");
    },
    onLineDelete: function(childView){
        var result = window.confirm("Êtes-vous sûr de vouloir supprimer cette ligne ?");
        if (result){
            childView.model.destroy(
                {
                    success: this.onDeleteSuccess,
                    error: this.onDeleteError
                }
            );
        }
    },
    showFilesRegion(){
        let edit = this.config.request('get:form_section', 'general')['edit'];
        let collection = this.facade.request(
            'get:collection',
            'attachments'
        );
        let view = new NodeFileCollectionView(
            {
                collection: collection,
                edit: edit
            }
        )
        this.showChildView('files', view);
    },
    showLinesRegion(){
        let section = this.config.request('get:form_section', 'lines');
        var collection = this.facade.request(
            'get:collection',
            'lines'
        );
        var view = new SupplierOrderLineTableView(
            {
                collection: collection,
                section: section,
            }
        );
        this.showChildView('linesRegion', view);
    },
    showMessages(){
        var model = new Bb.Model();
        var view = new MessageView({model: model});
        this.showChildView('messages', view);
    },
    showTotals(){
        let model = this.facade.request('get:model', 'total');
        var view = new TotalView({model: model});
        this.showChildView('totals', view);
    },
    showLogin: function(){
        var view = new LoginView({});
        this.showChildView('modalRegion', view);
    },
    onRender(){
        this.showFilesRegion();
        this.showSupplierOrderForm();
        this.showLinesRegion();
        this.showTotals();
        this.showMessages();
    },
    _showStatusModal(model) {
        console.log("Showing the status modal")
        var view = new StatusFormPopupView({action: model});
        this.showChildView('modalRegion', view);
    },
    formOk(){
        console.log("Checking that form is OK");
        var result = true;
        var errors = this.facade.request('is:valid');
        if (!_.isEmpty(errors)){
            console.log(errors);
            this.showChildView(
                'errors',
                new ErrorView({errors:errors})
            );
            result = false;
        } else {
            this.detachChildView('errors');
        }
        return result;
    },
    onStatusChange(action_model){
        console.log("Status changed asked")
        if (this.config.request('get:form_section', 'general')['edit']) {
            if (! action_model.get('status')){
                return;
            }
            // Prior to any status change, we want to save and make sure it went OK
            showLoader();
    
            if (action_model.get('status') != 'draft'){
                console.log("Status is not draft");
                if (! this.formOk()){
                    document.body.scrollTop = document.documentElement.scrollTop = 0;
                    hideLoader();
                    return;
                }
            }

            this.facade.request('save:all').then(
                () => {hideLoader(); this._showStatusModal(action_model)},
                () => {hideLoader(); displayServerError("Erreur pendant la sauvegarde")}
            );
        } else {
            this._showStatusModal(action_model);
        }
    },
});
export default MainView;
